package chapter06;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Consumer;
import java.util.function.Supplier;

public class LongAdder2AtomicLongTest {
    public static void main(String[] args) {
        for(int i=1;i<=5;i++){
            demo(()->new AtomicInteger(),(adder)->adder.incrementAndGet());
        }

        for(int i=1;i<=5;i++){
            demo(()-> new LongAdder(),(adder)-> adder.increment());
        }

    }


    /**
     *
     * @param addSupplier 生成累加器
     * @param action 做累加操作
     * @param <T>
     */
    public static <T> void demo(Supplier<T> addSupplier, Consumer<T> action){
        long startTime = System.currentTimeMillis();

        T adder=addSupplier.get();
        List<Thread> tds=new ArrayList<>();
        for(int i=0;i<4;i++){
            tds.add(new Thread(()->{
                for(int j=1;j<=500000;j++){
                    action.accept(adder);
                }
            }));
        }
        tds.forEach(Thread::start);
        for (Thread td : tds) {
            try {
                td.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        long endTime=System.currentTimeMillis();
        System.out.println("结果:"+adder+"运行时间："+(endTime-startTime));
    }
}

